import { showToast } from "vant"
import { ref, Ref } from "vue"
import { getCodeApi } from "../../apis/userApi"

/** 获取验证码 */
const codeMsg:Ref<string> = ref('获取验证码')
const phone:Ref<string> = ref('')
const set = ref()

async function codeEvt() {
    if(!(/^1[3-9]{1}[0-9]{9}$/.test(phone.value))) {
        showToast('请输入正确的手机号')
        return
    }
    if(codeMsg.value !== '获取验证码') return
    let res = await getCodeApi(phone.value)
    if(res.code === 200) {
        codeMsg.value = '重新获取(60s)'
        showToast('验证码' + res.data)
        localStorage.setItem('code', res.data)
        loopTimer(Date.now())
    } else {
        codeMsg.value = '获取验证码'
        showToast('获取验证码失败 请重试')
    }
}

/** 验证码倒计时 */
function loopTimer(st: number) {
    let timer = 60 - Math.ceil((Date.now() - st) / 1000)
    if (timer > 0) {
        codeMsg.value = `重新获取(${timer}s)`
        set.value = setTimeout(() => {
            loopTimer(st)
        }, 100)
    } else {
        codeMsg.value = '获取验证码'
    }
}

export {
    codeMsg,
    phone,
    codeEvt,
    set
}